package cn.itsource.config.rabbitmq;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 作用：声明交换机、声明队列、以及声明绑定关系
 */
@Configuration
public class RabbitmqConfig {

    public static final String EXCHANGE_HRM = "exchange_hrm";//交换机名称
    public static final String QUEUE_NAME_EMAIL = "queue_email";//邮件队列名称
    public static final String QUEUE_NAME_SMS = "queue_sms";//短信队列名称
    public static final String ROUTINGKEY_QUEUE_EMAIL = "#.email";//邮件队列的routingkey
    public static final String ROUTINGKEY_QUEUE_SMS = "#.sms";//邮件队列的routingkey

    //注册交换机
    @Bean
    public Exchange topicExchange(){
        //durable：设置持久化
        return ExchangeBuilder.topicExchange(EXCHANGE_HRM).durable(true).build();
    }
    //注册邮件队列-用来发邮件
    @Bean
    public Queue emailQueue(){
        return new Queue(QUEUE_NAME_EMAIL, true, false, false);
    }

    //注册短信队列-用来发短信
    @Bean
    public Queue smsQueue(){
        return new Queue(QUEUE_NAME_SMS, true, false, false);
    }

    //邮件队列绑定到交换机
    @Bean
    public Binding bindEmailQueue(){
        return BindingBuilder.bind(emailQueue()).to(topicExchange()).with(ROUTINGKEY_QUEUE_EMAIL).noargs();
    }

    //邮件队列绑定到交换机
    @Bean
    public Binding bindSmsQueue(){
        return BindingBuilder.bind(smsQueue()).to(topicExchange()).with(ROUTINGKEY_QUEUE_SMS).noargs();
    }

    //初始化RabbitAdmin对象
    @Bean
    public RabbitAdmin rabbitAdmin(ConnectionFactory connectionFactory) {
        RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
        // 只有设置为 true，spring 才会加载 RabbitAdmin 这个类
        rabbitAdmin.setAutoStartup(true);

        //下面设置目的：项目启动时，就创建交换机和队列
        //创建交换机
        rabbitAdmin.declareExchange(topicExchange());
        //创建对列
        rabbitAdmin.declareQueue(emailQueue());
        rabbitAdmin.declareQueue(smsQueue());

        return rabbitAdmin;
    }
}